package com.github.prontera.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.github.prontera.ApiVersion;
import com.github.prontera.client.BaseRequestListener;
import com.github.prontera.client.DownloadListener;
import com.github.prontera.client.OperationCanceledException;
import com.github.prontera.client.RestRequest;
import com.github.prontera.common.filter.IgnoreAuth;
import com.github.prontera.domain.Client;
import com.github.prontera.domain.IssueAnswer;
import com.github.prontera.model.response.ObjectDataResponse;
import com.github.prontera.service.ClientService;
import com.github.prontera.service.IssueAnswerService;
import com.github.prontera.util.DateTimeUtil;
import com.github.prontera.util.URLUtils;

/**
 * 客户端
 */
@RestController
@RequestMapping(value = ApiVersion.API_V1_PREFIX + "/download")
public class DownloadController {
	@Autowired
	private ClientService clientService;
	@Autowired
	private IssueAnswerService issueAnswerService;

	private void download(Long id,String uid, IssueAnswer issueAnswer) {
		String datePath = DateTimeUtil.formatDateTimetoString(DateTimeUtil.getSystemDate(), "yyyy\\MM\\dd");
		String httpDatePath = DateTimeUtil.formatDateTimetoString(DateTimeUtil.getSystemDate(), "yyyy/MM/dd");

		String imageIp = "http://image.yuejiulai.com";
		String videoIp = "http://video.yuejiulai.com";

		if (!new File("E:\\media2\\" + id +"\\" + datePath +  "\\").exists()) {
			new File("E:\\media2\\" + id + "\\" + datePath + "\\").mkdirs();
		}

		String[] imagePngUrls = issueAnswer.getImage().split("[//]");
		String imageFilename = imagePngUrls[imagePngUrls.length - 1];
		String imagehttpDatePath = imageIp + "/" + id + "/" + httpDatePath + "/" + imageFilename;

		String[] videoPngUrls = issueAnswer.getVideo().split("[//]");
		String videoFilename = videoPngUrls[videoPngUrls.length - 1];
		String videohttpDatePath = videoIp + "/" + id + "/" + httpDatePath + "/" + videoFilename;

		String[] headImagePngUrls = issueAnswer.getHeadImage().split("[//]");
		String headImageFilename = headImagePngUrls[headImagePngUrls.length - 1];
		String headImagehttpDatePath = imageIp + "/" + id + "/" + httpDatePath + "/" + headImageFilename;
		
		RestRequest request = new RestRequest(issueAnswer.getImage());
		request.addHeader("User-Agent",
				"Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request.download("E:\\media2\\" +id  + "\\" +  datePath+ "\\" + imageFilename, new DownloadListener() {

			public void onError(Exception ex) {

			}

			public void onProgress(float progress, float total) throws OperationCanceledException {

			}

			@Override
			public void onComplete(Object response) {

			}
		});

		request = new RestRequest(issueAnswer.getVideo());
		request.addHeader("User-Agent",
				"Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request.download("E:\\media2\\" +id  + "\\" + datePath + "\\" + videoFilename, new DownloadListener() {

			public void onError(Exception ex) {

			}

			public void onProgress(float progress, float total) throws OperationCanceledException {

			}

			@Override
			public void onComplete(Object response) {

			}
		});
		
		request = new RestRequest(issueAnswer.getHeadImage());
		request.addHeader("User-Agent",
				"Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request.download("E:\\media2\\" + id + "\\" + datePath + "\\" + headImageFilename, new DownloadListener() {

			public void onError(Exception ex) {

			}

			public void onProgress(float progress, float total) throws OperationCanceledException {

			}

			@Override
			public void onComplete(Object response) {

			}
		});
		
		Client client = new Client();
		client.setId(id);
		client.setHeadImage(headImagehttpDatePath);
		clientService.update(client);
		
		issueAnswer.setVideo(videohttpDatePath);
		issueAnswer.setImage(imagehttpDatePath);
		issueAnswerService.insert(issueAnswer);
		
		startDownAvatar(id, uid);
		
	}
	
	@IgnoreAuth
	@RequestMapping(value = "getUserInfo", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Object> getUserInfo(@RequestBody String uid)  {
		Map<String, String> params = new HashMap<String, String>();
		
		String uri = URLUtils.append("http://120.25.135.13//api/user/"+uid, params);
		RestRequest request = new RestRequest(uri);
		request.addHeader("User-Agent","Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request.addHeader("X-Api-Token", "42E4AF30571346CCA063AA5C1A260C00");
		Object objectNode = request.get();
		System.out.println(objectNode);
		
		
		String uri2 = URLUtils.append("http://120.25.135.13/api/user/"+uid+"/videos2?v=2.7.2&dev=android&dev_version=8.0.0&dev_name=DUK-AL20&uuid=ea8fceffc05b242f", params);
		RestRequest request2  = new RestRequest(uri2);
		request2 .addHeader("User-Agent","Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request2 .addHeader("X-Api-Token", "42E4AF30571346CCA063AA5C1A260C00");
		
		String conten=(String)request2.get();
		System.out.println(conten);
		//startdDwnVedio(uid,conten);
		
		return new ObjectDataResponse<Object>(conten);
	}
	
	private void startDownAvatar(Long clientId,String uid) {
		Map<String, String> params = new HashMap<String, String>();
		String uri = URLUtils.append("http://120.25.135.13//api/user/"+uid, params);
		RestRequest request = new RestRequest(uri);
		request.addHeader("User-Agent","Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request.addHeader("X-Api-Token", "42E4AF30571346CCA063AA5C1A260C00");
		request.get(new BaseRequestListener() {
			public void onError(Exception ex) {

			}

			public void onComplete(Object response) {
				String objectNode = (String) response;
				System.out.println(objectNode);
				JSONObject jsonObject = new JSONObject(objectNode);
				JSONArray jsonArray = jsonObject.getJSONObject("data").optJSONArray("photos");
				System.out.println(jsonArray.length());
				List<String> avatars=new ArrayList<String>();
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject skObj = jsonArray.getJSONObject(i);
					if (skObj != null) {
						String avatar = skObj.getString("url");
						System.out.println("-----------------------1-----------avatar["+avatar+"]");
						String datePath = DateTimeUtil.formatDateTimetoString(DateTimeUtil.getSystemDate(), "yyyy\\MM\\dd");

						String imageIp = "http://image.yuejiulai.com";

						if (!new File("E:\\media2\\" + clientId + "\\" + datePath + "\\").exists()) {
							new File("E:\\media2\\" +clientId  + "\\" + datePath + "\\").mkdirs();
						}

						String[] imagePngUrls = avatar.split("[//]");
						String imageFilename = imagePngUrls[imagePngUrls.length - 1];
						String imagehttpDatePath = imageIp + "/" + clientId + "/" + datePath + "/" + imageFilename;

						System.err.println("E:\\media2\\" + clientId + "\\" + datePath + "\\" + imageFilename);
						
						
						imagehttpDatePath=imagehttpDatePath.replace("\\", "/");
						
						avatars.add(imagehttpDatePath);
						
						RestRequest request = new RestRequest(avatar);
						request.addHeader("User-Agent",
								"Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
						request.download("E:\\media2\\" + clientId + "\\" + datePath + "\\" + imageFilename, new DownloadListener() {

							public void onError(Exception ex) {

							}

							public void onProgress(float progress, float total) throws OperationCanceledException {

							}

							@Override
							public void onComplete(Object response) {
								
							}
						});
					}
				}
				
				String pString=StringUtils.join(avatars,",");
				if(!StringUtils.isEmpty(pString)){
					Client client = new Client();
					client.setId(clientId);
					client.setPhotos(pString);
					try {
						clientService.update(client);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});
	}
	 
	private void startdDwnVedio(String uid,String objectNode) {
		System.out.println(objectNode);
		JSONObject jsonObject = new JSONObject(objectNode);
		JSONArray jsonArray = jsonObject.getJSONArray("data");
		System.out.println(jsonArray.length());
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject jsonObj = jsonArray.getJSONObject(i);
			JSONObject skObj = jsonObj.optJSONObject("sk");
			JSONObject userObj = skObj.getJSONObject("user");
			String avatar = userObj.getString("avatar");
			
			Client client = clientService.findOne(new Client() {
				private static final long serialVersionUID = 1L;
				{
					setUid(uid);
				}
			});

			JSONObject videoObj = skObj.getJSONObject("video");
			IssueAnswer findIssueAnswer = new IssueAnswer();
			findIssueAnswer.setVideo(videoObj.getString("video_url"));
			if (issueAnswerService.count(findIssueAnswer) > 0) {
				continue;
			}
			IssueAnswer issueAnswer = new IssueAnswer();
			issueAnswer.setType(1);
			issueAnswer.setHeadImage(userObj.getString("avatar"));
			issueAnswer.setClientId(client.getId());
			issueAnswer.setImage(videoObj.optString("cover_url"));
			issueAnswer.setIssureClientId(client.getId());
			issueAnswer.setVideo(videoObj.getString("video_url"));

			download(client.getId(),uid, issueAnswer);
		}
	}

}
